import { memo, useEffect } from 'react';
import { Alert, Drawer, Layout } from 'tdesign-react';
import throttle from 'lodash/throttle';
import { useAppSelector, useAppDispatch } from 'modules/store';
import { selectGlobal, toggleSetting, toggleMenu, ELayout, switchTheme, switchColor } from 'modules/global';
import Setting from './components/Setting';
import AppLayout from './components/AppLayout';
import Style from './index.module.less';
import { startWS, onWSMessage, offWSMessage, WSMessage } from '@/services/websocket';
import PubSub from 'pubsub-js';
import GlobalNotification from '@/components/GlobalNotification';

export default memo(() => {
  const globalState = useAppSelector(selectGlobal);
  const dispatch = useAppDispatch();
  const AppContainer = AppLayout[globalState.isFullPage ? ELayout.fullPage : globalState.layout];

  useEffect(() => {
    // 初始化主题
    dispatch(switchTheme(globalState.theme));
    // 初始化主题色
    dispatch(switchColor(globalState.color));
    // WebSocket全局连接
    startWS();
    const handleMsg = (msg: WSMessage) => {
      console.log('收到WebSocket消息:', msg);
      // 发布预约消息
      if (msg.type === 'reservation') {
        console.log('发布预约消息');
        PubSub.publish('reservationMessage', msg);
      }
      // 发布审批消息
      if (msg.type === 'approval') {
        console.log('发布审批消息');
        PubSub.publish('approvalMessage', msg);
      }
    };
    onWSMessage(handleMsg);
    const handleResize = throttle(() => {
      if (window.innerWidth < 900) {
        dispatch(toggleMenu(true));
      } else if (window.innerWidth > 1000) {
        dispatch(toggleMenu(false));
      }
    }, 100);
    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
      offWSMessage(handleMsg);
    };
  }, []);

  return (
    <>
      <Layout className={Style.panel}>
        <GlobalNotification />
        <AppContainer />
        <Drawer
          destroyOnClose
          visible={globalState.setting}
          size='458px'
          footer={false}
          header='页面配置'
          onClose={() => dispatch(toggleSetting())}
        >
          <Setting />
        </Drawer>
      </Layout>
    </>
  );
});